// pages/venuesInfo/venuesInfo.js

const config = require('../../libs/config'); 
Page({
  data: {
    venuesInfo: null,
    loading: true,
    error: false,
    isExpanded: false,
    truncatedText: '',
    venueId: null,
    //地图新增数据
    latitude: '',
    longitude: '',
    address: '',
    name: ''
  },

  async onLoad(options) {
    this.setData({ venueId: options.id })
    await this.loadDetailData(options.id)
    this.getLatLngByAddress()
  },

  onPullDownRefresh() {
    this.refreshData(true)
  },

  async refreshData(forceReload = false) {
    this.setData({ loading: true })
    await this.loadDetailData(this.data.venueId, forceReload)
    wx.stopPullDownRefresh()
  },

  async loadDetailData(id, forceReload = false) {
    try {
      console.log('[初始化] 开始加载场馆详情数据，ID:', id)
      wx.showLoading({ title: '加载中...' })
      const numericId = parseInt(id)

      if (!forceReload) {
        console.log('[缓存查询] 尝试读取缓存数据...')
        const cacheData = await this.getCacheData(numericId)
        if (cacheData) {
          console.log('[缓存命中] 使用缓存数据')
          this.handleSuccessData(cacheData)
          console.log(cacheData,'cacheData');
          return
        }
        console.log('[缓存状态] 未找到有效缓存数据')
      }

      console.log('[云服务] 调用云函数获取最新数据...')
      const res = await wx.cloud.callFunction({ 
        name: 'getVenuesList'
      })

      console.log('[云响应] 接收云函数响应:', res)
      if (res.result.code === 200) {
        console.log('[数据处理] 开始解析云端数据...')
         // 合并 threeBase 和 nNode 的数据块
        const contentBlocks = [
          ...(res.result.threeBase || []),
          ...(res.result.nNode || [])
        ];
        const processedData = this.processCloudData(contentBlocks)
        console.log(`[数据统计] 共处理 ${processedData.length} 条场馆数据`)
        const foundItem = processedData.find(item => item.id === numericId)
        if (foundItem) {
          console.log('[数据匹配] 找到目标场馆数据:', foundItem)
          this.handleSuccessData(foundItem)
        } else {
          console.error('[数据异常] 未找到对应ID的场馆数据，ID:', numericId)
          this.showError()
        }
      } else {
        console.error('[服务异常] 服务器返回错误状态码:', res.result.code)
        throw new Error('服务器返回错误')
      }
    } catch (e) {
      console.error('[加载失败] 数据加载异常:', e)
      console.warn('[回退机制] 尝试缓存数据回退...')
      const cacheData = await this.getCacheData(parseInt(id))
      if (cacheData) {
        console.log('[缓存回退] 使用缓存数据成功')
        this.handleSuccessData(cacheData)
        wx.showToast({ title: '数据更新失败，显示缓存内容', icon: 'none' })
      } else {
        console.error('[严重错误] 无可用缓存数据')
        this.showError()
      }
    } finally {
      console.log('[流程结束] 数据加载流程完成')
      wx.hideLoading()
    }
  },

  // 从缓存获取数据
  async getCacheData(id) {
    try {
      console.log('[缓存系统] 开始查询缓存，目标ID:', id);
  
      const { data: cache } = await wx.getStorage({ 
        key: 'threeSubTitleData'
      }).catch(err => {
        if (err.errMsg.includes('data not found')) {
          console.log('[缓存状态] 无缓存数据');
          return { data: null };
        }
        throw err;
      });
  
      // 校验缓存结构和时效性
      if (!cache?.content) {
        console.log('[缓存结构] 缓存内容不存在或格式错误');
        return null;
      }
  
      const CACHE_VALIDITY = 3600000;
      if (Date.now() - cache.timestamp > CACHE_VALIDITY) {
        console.log(`[缓存时效] 数据已过期 (${Math.floor((Date.now() - cache.timestamp) / 1000)}秒)`);
        return null;
      }
  
      // 合并 threeBase 和 nNode 的数据块
      const contentBlocks = [
        ...(cache.content.threeBase || []),
        ...(cache.content.nNode || [])
      ];
  
      console.log(
        `[缓存结构] 开始遍历 ${contentBlocks.length} 个内容区块 ` +
        `(threeBase: ${cache.content.threeBase?.length || 0}, ` +
        `nNode: ${cache.content.nNode?.length || 0})`
      );
  
      let matchCount = 0;
  
      // 遍历所有数据块
      const targetItem = contentBlocks.reduce((result, contentBlock, index) => {
        if (!contentBlock.data) {
          console.warn(`[缓存结构] 第${index + 1}个区块缺少data字段`);
          return result;
        }
  
        // 统一处理数组格式
        const dataItems = Array.isArray(contentBlock.data) 
          ? contentBlock.data 
          : [contentBlock.data];
  
        // ID 匹配查询
        const match = dataItems.find(item => Number(item.id) === Number(id));
        if (match) {
          console.log(`[缓存命中] 在 ${contentBlock._id} 区块找到匹配项`);
          matchCount++;
          return match;
        }
        return result;
      }, null);
  
      // 返回格式化结果
      if (targetItem) {
        console.log(`[缓存结果] 成功找到 ${matchCount} 个匹配项`);
        return {
          id: targetItem.id,
          name: targetItem.className || '未命名场馆',
          image: targetItem.img || '',
          opentime: targetItem.opentime || '全天',
          address: targetItem.address || '默认地址',
          function: targetItem.function || [],
          introduction: targetItem.introduction || '',
          otherPic: targetItem.otherPic || [],
          tab: targetItem.tab || [],
          ...targetItem // 保留原始字段
        };
      }
  
      console.log('[缓存结果] 未找到匹配数据');
      return null;
    } catch (error) {
      console.error('[缓存异常] 查询失败:', error);
      return null;
    }
  },

  
// 刷新
  processCloudData(cloudData) {
    console.log('[数据加工] 处理原始云数据')
    const processed = cloudData.flatMap(base => 
       base.data.map(item => ({
        id: parseInt(item.id),
        baseName: base.name,
        basePic: base.pic,
        image: item.img || '',
        name: item.className || '未命名场馆',
        opentime: item.opentime || '全天',
        address: item.address || '默认地址',
        function: item.function || [],
        introduction: item.introduction || '',
        otherPic: item.otherPic || [],
        tab: item.tab || [],
      }))
    )
    console.log('[数据转换] 最终数据结构:', processed.slice(0,1))
    return processed
  },

  handleSuccessData(data) {
    console.log('[状态更新] 准备更新页面数据')
    this.setData({
      venuesInfo: data,
      truncatedText: this.truncateText(data.introduction),
      loading: false
    })
    console.log('[渲染完成] 页面数据更新完毕')
  },

  truncateText(text = '', length = 100) {
    return text.length > length ? text.substr(0, length) + '...' : text
  },

  showError() {
    this.setData({ 
      loading: false,
      error: true 
    })
    wx.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  },

  toggleExpand() {
    this.setData({ 
      isExpanded: !this.data.isExpanded,
      truncatedText: this.data.isExpanded ? 
        this.truncateText(this.data.venuesInfo.introduction) : 
        this.data.venuesInfo.introduction
    })
  },
  
  // 根据地名获取经纬度
  getLatLngByAddress() {
    // 从 config 获取密钥（需确保文件路径正确）
    const apiKey = config.Config.keyWeb;
    // 对地址进行 URL 编码（避免特殊字符问题）
    const encodedAddress = encodeURIComponent(this.data.venuesInfo.name); 
    const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodedAddress}&key=${apiKey}`;

    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        console.log('API响应:', res.data); // 调试日志
        if (res.data.status === '1' && res.data.geocodes?.length > 0) {
          const location = res.data.geocodes[0].location;
          const [longitude, latitude] = location.split(',');
          this.setData({
            latitude: latitude,
            longitude: longitude,
            address: res.data.geocodes[0].formatted_address,
            name: this.data.venuesInfo.name
          });
        } else {
          // 明确显示错误原因（如密钥无效、地址不存在）
          const errorMsg = res.data.info || '未知错误';
          wx.showToast({ title: `地址解析失败: ${errorMsg}`, icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({ title: '网络请求异常', icon: 'none' });
      }
    });
  },

  // 打开地图
  async openLocation() {
    if (!this.data.venuesInfo) {
      wx.showToast({ title: '场馆数据未加载', icon: 'none' });
      return;
    }
    
    if (!this.data.latitude || !this.data.longitude) {
      await this.getLatLngByAddress();
    }
    wx.openLocation({
      latitude: Number(this.data.latitude),
      longitude: Number(this.data.longitude),
      name: this.data.name || '目标位置',
      address: this.data.address,
      scale: 18,
      success: () => console.log('地图打开成功'),
      fail: (err) => {
        console.error('打开失败:', err);
        wx.showToast({ title: '请检查地图权限', icon: 'none' });
      }
    });
  },

  // 图片预览处理
  handlePreviewImage(e) {
    const urls = e.currentTarget.dataset.urls;
    const current = e.currentTarget.dataset.current;
  
    if (!urls || urls.length === 0) {
      wx.showToast({ title: '暂无更多图片', icon: 'none' });
      return;
    }

    wx.previewImage({
      current: current,       // 当前显示图片的http链接
      urls: urls,             // 需要预览的图片http链接列表
      success: (res) => {
        console.log('预览打开成功', res);
      },
      fail: (err) => {
        console.error('预览失败:', err);
        wx.showToast({ title: '图片加载失败', icon: 'none' });
      }
    });
  }
});